define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'coll/analysis/index' + location.search,
                    // add_url: 'coll/analysis/add',
                    // edit_url: 'coll/analysis/edit',
                    // del_url: 'coll/analysis/del',
                    multi_url: 'coll/analysis/multi',
                    table: 'analysis',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                rowStyle:function(row, index){
                    if (row.ystatus == 4) {
                        return{
                            css:{
                                color:'red'
                            }
                        }
                    }else{
                        return{}
                    }
                },
                columns: [
                    [
                        {checkbox: true,formatter:function(value,row){
                                if(row['ystatus'] >2){
                                    return {
                                        disabled: true,
                                    }
                                }
                                // return '<input data-index="0" name="btSelectItem" type="checkbox">';
                            }},
                        {field: 'id', title: __('Id'),class:'aid', operate:false},
                        {field: 'source', title: __('Source'),searchList: $.getJSON(Config.this_url+"/config/zaxconfig?states=18")},
                        {field: 'storehouse.name', title: __('所属仓库'),searchList: $.getJSON(Config.this_url+"/config/zaxconfig?states=1")},

                        {field: 'operator', title: __('Operator')},
                        {field: 'company', title: __('Company')},

                        {field: 'is_income', title: __('Is_income'), searchList: {1:__('收入'),2:__('支出')}, formatter: Table.api.formatter.status},
                        // {field: 'controller', title: __('Controller')},
                        {field: 'settle_name', title: __('settle_name'),operate:'LIKE'},
                        {field: 'number', title: __('number')},
                        {field: 'analysis.createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},
                        {field: 'cost', title: __('Cost'), operate:false},//operate:'BETWEEN',
                        {field: 'costprice', title: __('成本'),operate:false},
                        {field: 'profit', title: __('毛利'),operate:false},
                        {field: 'maoli', title: __('毛利率'),operate:false},
                        {field: 'paymoney', title: __('已付/已收'), operate:false},
                        // {field: 'status', title: __('status'), searchList: {"1": '热门', "2":'首页', "3": '推荐'}, addClass: 'selectpicker',data: 'multiple', operate: 'FIND_IN_SET'},
                        // {field: 'status', title: __('Status'), addClass: 'selectpicker',data: 'multiple', operate: 'in', searchList: $.getJSON(Config.this_url+"/config/zaxconfig?states=14")},
                        {field: 'status', title: __('Status'), addClass: 'selectpicker',data: 'multiple', operate: 'in',searchList: {"1": '待处理', "2":'已收款未收齐', "3":"已完成","4": '中止'}},
                        {field: 'explain', title: __('备注说明'), operate:false},
                        // {field: 'status', title: __('Status'),class: 'selectpage',operate:'FIND_IN_SET', formatter: Table.api.formatter.label,searchList: $.getJSON(Config.this_url+"/config/zaxconfig?states=14")},
                        {field: 'operate', title: __('Operate'), table: table, buttons: [
                                // {
                                //     name: 'pay',
                                //     title: __('付/收款'),
                                //     classname: 'btn btn-xs btn-success btn-click editstatus',
                                //     icon: 'fa fa-jpy',
                                //     hidden:function(row){
                                //         if(row.ystatus >2){
                                //             return true;
                                //         }
                                //     },
                                //     click: function(data){
                                //         var aid = $(this).parents('tr').find('.aid').html()
                                //         layer.open({
                                //             type: 2, // 1-在content中写html代码， 2-在content中写src路径
                                //             area: ['50%', '90%'],
                                //             title: "收付款",
                                //             content: 'analysis/pay?ids='+aid,
                                //             // content: Config.this_url+'/purchase/requisition',
                                //         })
                                //     }},
                                // {
                                //     name: 'cancelbill',
                                //     title: __('单据红冲'),
                                //     classname: 'btn btn-xs btn-danger btn-click editstatus',
                                //     icon: 'fa fa-xing',
                                //     hidden:function(row){
                                //         if(row.ystatus == 3){
                                //             return true;
                                //         }
                                //     },
                                //     click: function(data){
                                //         var aid = $(this).parents('tr').find('.aid').html()
                                //         layer.open({
                                //             type: 2, // 1-在content中写html代码， 2-在content中写src路径
                                //             area: ['50%', '90%'],
                                //             title: "收付款",
                                //             content: 'analysis/pay?ids='+aid,
                                //             // content: Config.this_url+'/purchase/requisition',
                                //         })
                                //     }},
                            ], events: Table.api.events.operate, formatter: Table.api.formatter.operate}
                    ]
                ]
            });
            // 当表格数据加载完成时
            table.on('load-success.bs.table', function (e, data) {
                console.log(data)
                $('#allcost').html(data.allcost)
                $('#yescost').html(data.yescost)
                $('#notcost').html(data.notcost)
                //这里可以获取从服务端获取的JSON数据
                // console.log(data);
                //这里我们手动设置底部的值
                // $("#num").text(data.num);
                // $("#price").text(data.price);
                // $('#getcount').click()
            });
            $('.commonsearch-table').on('click','.btn-success',function () {
                // $('#getcount').click()
            })
//             $('#getgather').click(function () {
//                 layer.load(1);
// //此处演示关闭
//                 that = $(this)
//                var data = $('form').serialize();
//
//                 var url = Config.this_url+'/coll/analysis/getcount';
//                $.post(url,{data:data},function (res) {
//                    that.find('#allcost').html(res.allcost)
//                    that.find('#yescost').html(res.yescost)
//                    that.find('#notcost').html(res.notcost)
//                })
//                setTimeout(function(){
//                     layer.closeAll('loading');
//                 }, 2000);
//             })

            $('.batchsss').click(function () {
                layer.open({
                    type: 2, // 1-在content中写html代码， 2-在content中写src路径
                    area: ['100%', '100%'],
                    title: "收款单",
                    // content: url,
                    content: Config.this_url+'/coll/analysis/batchsss'
                })
            })


            $('.batch').click(function () {
                var ids = [];
                $('tbody').find('tr').each(function () {
                    if($(this).find('input').prop('checked')){
                        ids.push($(this).find('.aid').html())
                    }
                })
                if(ids.length >0){
                    var url = Config.this_url+'/coll/analysis/check';
                    // console.log(url)
                    // return false;
                    $.post(url,{ids:JSON.stringify( ids )},function (res) {
                        if(res.code == 1){
                            layer.open({
                                type: 2, // 1-在content中写html代码， 2-在content中写src路径
                                area: ['80%', '90%'],
                                title: "批量处理",
                                // content: url,
                                content: Config.this_url+res.url+'?ids='+ids.join(','),
                            })
                        }else{
                            layer.msg(res.msg)
                        }

                    })
                }else{
                    layer.msg('请选择')
                }
            })

            $('table').on('dblclick','td',function(){
                var aid = $(this).parents('tr').find('.aid').html()
                var url = Config.this_url+'/coll/analysis/jump?ids='+aid
                $.post(url,{},function (res) {
                    if(res.code==0){
                        layer.msg(res.msg)
                        return false;
                    }
                    layer.open({
                        type: 2, // 1-在content中写html代码， 2-在content中写src路径
                        area: ['80%', '90%'],
                        title: "详情",
                        // content: url,
                        content: Config.this_url+'/'+res.data,
                    })
                })
            });
            $('.btn-export').click(function () {
                var url = Config.this_url+'/coll/analysis/export'
                layer.open({
                    type: 2, // 1-在content中写html代码， 2-在content中写src路径
                    area: ['30%', '70%'],
                    // area: ['20%', '60%'],
                    title: "导出选择",
                    content: url,
                    // content: Config.this_url+'/purchase/requisition',
                })
            })



            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
        },
        batch: function () {
            Controller.api.bindevent();
        },
        batchs: function () {
            Controller.api.bindevent();
        },
        export: function () {
            $('.btn-embossed').click(function () {
                // console.log($(".checkstatus").val())
                // console.log()
                // console.log($("input[ name='status[]']").val())
                // console.log($("input[ name='end_time']").val())
                layer.load(0,{time:5*1000});
                //
                window.location.href = Config.this_url+'/coll/analysis/exportExcel?status='+$('#c-flag').val()+'&start_time='+$("input[ name='start_time']").val()+'&end_time='+$("input[ name='end_time']").val()+'&customer_id='+$("#c-customer_id").val()+'&supplier_id='+$("#c-supplier").val()+  '&storehouse_id='+$("#c-storehouse_id").val()+'&admin_id='+$('#c-admin_id').val()+'&type_id='+$('#type_id').val()
                return false;
            })
            $("#type_id").change(function(){
                if($(this).val() == 1){
                    $('.c-customer_id').attr('style','display:')
                    $('.c-supplier').attr('style','display:none')
                }else{
                    $('.c-customer_id').attr('style','display:none')
                    $('.c-supplier').attr('style','display:')
                }
            });
            Controller.api.bindevent();
        },
        pay: function () {

            Controller.api.bindevent();
        },
        batchsss: function () {
            $('#pay_type').change(function () {
                console.log($(this).val())
                if($(this).val() == 1){
                    $('.customer').attr('style','display:')
                    $('.supplier').attr('style','display:none')
                }
                if($(this).val() == 2){
                    $('.customer').attr('style','display:none')
                    $('.supplier').attr('style','display:')
                }
            })
            $(".btn-add").click(function () {
                pay_type = $('#pay_type').val()
                if(pay_type == 1){ //收入
                    source_id = $('#c-customer_id').val()

                }else{ //支出
                    source_id = $('#c-supplier').val()
                }
                if(source_id == ''){
                    layer.msg('尚未选择供应商或者客户')
                    return false;
                }
                // console.log(pay_type)
                // console.log(source_id)
                // if($('#c-storehouse_id').val()== 0 ){
                //     layer.msg('未选中出库仓库')
                //     return false;
                // }
                layer.open({
                    type: 2, // 1-在content中写html代码， 2-在content中写src路径
                    area: ['70%', '90%'],
                    title: "选择单据",
                    content: 'seach?pay_type='+pay_type+'&source_id='+source_id,
                })
            })
            Controller.api.bindevent();
        },
        seach:function(){
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'coll/analysis/seach' + location.search,
                    table: '',
                }
            });

            var table = $("#table");
            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'weigh',
                pageSize:15,
                // searchFormVisible: true,
                searchFormTemplate: 'customformtpl',
                columns: [
                    [
                        // {checkbox: true,operate:false},
                        {field: 'id', title: 'ID', operate: false,class:'sid'},
                        {field: 'source', title: __('数据来源'),  operate: false},
                        {field: 'house_name', title: __('所属仓库')},
                        {field: 'operator', title: __('经手人'), align: 'left'},
                        {field: 'number', title: __('单据编号')},
                        {field: 'paymoney', title: __('费用'),class: 'cost'},
                        {field: 'createtime', title: __('Create time'), formatter: Table.api.formatter.datetime, operate: 'RANGE', addclass: 'datetimerange'},
                        {checkbox: true,operate:false,class: 'ischange'},
                    ]
                ]
            });
            arr = [];
            $(table).on('change','input',function () {
                var index = $("table input").index(this)
                if(index == 0){//全选
                    $('tbody').find("tr").each(function(){
                        var sid = $(this).find('.sid').html();
                        if(sid != undefined){
                            delarr(sid)
                            arr.push({'id':sid,cost:$(this).find('.cost').html()})
                            // console.log(arr)
                        }
                    });
                    count()
                }else {
                    if($(this).hasClass('.ischange')){
                        console.log('这是全选')
                    }
                    var sid = $(this).parents('tr').find('.sid').html();
                    if($(this).prop('checked')){
                        arr.push({'id':sid,cost:$(this).parents('tr').find('.cost').html()})
                        count()
                    }else{
                        delarr(sid)
                        count()
                    }
                }
            })
            function delarr(sid){
                for (var i=0;i<arr.length;i++){
                    if(arr[i].id == sid){
                        arr.splice(i,1);
                    }
                }
            }

            function count(){
                var allcost = 0;
                for (var i=0;i<arr.length;i++){
                    allcost+=arr[i].cost*1
                }
                // console.log(allcost)
                $('#allcost').html(allcost.toFixed(2))
            }

            $('.sure').click(function () {
                if(arr.length <1){
                    layer.msg('请先选择处理单据')
                    return false
                }
                parent.getanalysis(arr);
                var index = parent.Layer.getFrameIndex(window.name);
                parent.Layer.close(index);
            })



            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            },
        }
    };
    return Controller;
});